package com.ly.mp.busicen.rule.flow.action.plugin;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.ly.mp.busicen.rule.flow.FlowException;
import com.ly.mp.busicen.rule.flow.FlowSpelUtil;
import com.ly.mp.busicen.rule.flow.IDataVolume;
import com.ly.mp.busicen.rule.flow.action.ActionExecuteBase;
import com.ly.mp.busicen.rule.flow.action.ActionResult;
import com.ly.mp.busicen.rule.flow.action.IAction;
import com.ly.mp.busicen.rule.flow.action.IActionResult;
import com.ly.mp.busicen.rule.flow.action.IActionResult.Signal;
import com.ly.mp.busicen.rule.flow.engine.db.BusicenSqlMapper;

public class ActionExecuteDataCheck extends ActionExecuteBase{
	
	Logger log = LoggerFactory.getLogger(ActionExecuteDataCheck.class);
	
	
	@Override
	public IActionResult execute(IAction action, IDataVolume dataVolume) {
		ActionResult result = ActionResult.create();
		result.action(action.action());
		try {
			BusicenSqlMapper busicenSqlMapper = BusicenSqlMapper.create();
			Object data = dataVolume;
			if (!StringUtils.isEmpty(action.extKey())) {
				data = FlowSpelUtil.spelGetData(action, action.extKey());
			}
			data = wrapperUserData(data);
			Map<String, Object> resultMap = busicenSqlMapper.selectOne(action.content(), data);
			result.data(resultMap);
			dataVolume.ext().put(action.action(), resultMap);
			if (resultMap!=null&&resultMap.size()>=2&&resultMap.containsKey("flag")) {
				String flag = resultMap.get("flag").toString();
				String nextActionLable = String.valueOf(resultMap.get("action"));
				if ("S".equals(flag)) {					
					result.signal(Signal.CONTINUE);
					result.msg(action.msg());
					result.nextAction(defaultNextActionCode(action, nextActionLable));
					log.info("业务规则校验节点{}校验结果为继续，下一动作节点为{}",action.action(),result.nextAction());
				}else {
					result.signal(Signal.BREAK);
					result.msg(action.msg());
					log.info("业务规则校验节点{}校验结果为中断",action.action());
				}
			}else {				
				result.signal(Signal.EXCPT);
				String error = String.format("[%s]返回节点少于两个，至少包含flag,action", action.action());
				result.excpt(new FlowException(error));
			}
		} catch (Exception e) {
			result.signal(Signal.EXCPT);
			result.excpt(e);
		}
		return result;
	}
}
